package com.dominator.serviceImpl;

import com.dominFramework.core.typewrap.Dto;
import com.dominFramework.core.typewrap.Dtos;
import com.dominFramework.core.utils.SystemUtils;
import com.dominator.enums.ReqEnums;
import com.dominator.mybatis.dao.*;
import com.dominator.repository.DaoAccount;
import com.dominator.repository.DaoMerchantAccount;
import com.dominator.repository.DaoQrLotteryTicket;
import com.dominator.repository.DaoUser;
import com.dominator.service.ApiCommonService;
import com.dominator.service.ApiMerchantService;
import com.dominator.service.ApiWzlService;
import com.dominator.utils.api.ApiMessage;
import com.dominator.utils.api.ApiMessageUtil;
import com.dominator.utils.api.ApiUtils;
import com.dominator.utils.encode.MerchantAESUtil;
import com.dominator.utils.encode.WzlEncryptUtil;
import com.dominator.utils.exception.ApiException;
import com.dominator.utils.system.Constants;
import com.dominator.utils.system.PropertiesLoader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Slf4j
public class ApiMerchantServiceImpl implements ApiMerchantService {

    public static PropertiesLoader propertiesLoader = new PropertiesLoader("sysconfig.properties");

    @Autowired
    DaoUser daoUser;
    @Autowired
    DaoAccount daoAccount;


    @Autowired
    DaoMerchantAccount daoMerchantAccount;

    @Autowired
    ApiWzlService apiWzlService;

    @Autowired
    T_merchantDao tMerchantDao;

    @Autowired
    DaoQrLotteryTicket qrLotteryTicketDao;
    @Autowired
    T_qr_lottery_ticketDao t_qr_lottery_ticketDao;

    @Autowired
    ApiCommonService apiCommonService;


    /**
     * 商户签名认证
     * @param dto
     * @throws ApiException
     */
    public void checkMerchantToken(Dto dto)throws ApiException{
        ApiUtils.checkParam(dto,"merchantToken,merchantId");
        String decode=null;
        decode=MerchantAESUtil.getInstance().decrypt(dto.getString("merchantToken"));
        String merchantId=decode.split("_")[0];
        String appSercret=decode.split("_")[1];
        String timestamp=decode.split("_")[2];
        long timeMinus=System.currentTimeMillis()-Long.parseLong(timestamp);
        if (SystemUtils.isEmpty(merchantId)||SystemUtils.isEmpty(appSercret)){
            System.out.println(ReqEnums.MERCHANT_SECRET_ERROR);
            throw new ApiException(ReqEnums.MERCHANT_VERIFY_ERROR);
        }
        T_merchantPO tMerchantPO= tMerchantDao.selectByKey(merchantId);
        if (SystemUtils.isEmpty(tMerchantPO)){
            System.out.println(ReqEnums.MERCHANT_IS_NOT_EXSIT);
            throw new ApiException(ReqEnums.MERCHANT_VERIFY_ERROR);
        }else if (!appSercret.equals(tMerchantPO.getApp_sercet())){
            System.out.println(ReqEnums.MERCHANT_SECRET_ERROR);
            throw new ApiException(ReqEnums.MERCHANT_VERIFY_ERROR);
        }else if (!"-1".equals(tMerchantPO.getIp())&&!dto.getString("ip").equals(tMerchantPO.getIp())){
            System.out.println(ReqEnums.MERCHANT_IP_ERROR);
            throw new ApiException(ReqEnums.MERCHANT_VERIFY_ERROR);
        }else if (timeMinus> Constants.MERCHANT_TOKEN_TIME||timeMinus<0){
            System.out.println(ReqEnums.MERCHANT_VERIFY_TIMEOUT);
            throw new ApiException(ReqEnums.MERCHANT_VERIFY_ERROR);
        }
        dto.put("merchantNum",tMerchantPO.getMerchant_num());

    }



    @Override
    public ApiMessage getMerchantUnionLoginParams(Dto dto) throws ApiException {
        checkMerchantToken(dto);
        ApiUtils.checkParam(dto,"phoneNum");

        if (SystemUtils.isEmpty(daoUser.selectByPhoneNum(dto.getString("phoneNum")))){
             daoUser.createPhoneUser(dto);
        }
        //联合登录
        System.out.println("加密前:"+dto.getString("phoneNum")+"_fenful_"+dto.getString("merchantNum"));
        String enString1 = null;
        try {
            enString1 = WzlEncryptUtil.getInstance().encrypt(dto.getString("phoneNum")+"_fenful_"+dto.getString("merchantNum"));
        } catch (Exception e) {
            throw new ApiException(ReqEnums.ENCODE_ERROR);
        }
        System.out.println("加密后的内容："+enString1);
        Dto resDto=Dtos.newDto();
        resDto.put("baseUrl",propertiesLoader.getProperty("union_login_url"));
        resDto.put("uniqueid",enString1);
        return ApiMessageUtil.success(resDto);
    }

    @Override
    public ApiMessage merchantLotteryLimit(Dto dto) throws ApiException {
        checkMerchantToken(dto);
        //查询余票
        Integer res=qrLotteryTicketDao.countTicketByMerchantId(Dtos.newDto("merchantId",dto.getString("merchantId")));
        return ApiMessageUtil.success(res);
    }

    @Override
    public ApiMessage merchantLotterySend(Dto dto) throws ApiException {
        checkMerchantToken(dto);
        return apiWzlService.lotteryQrcodeSend(dto);
    }

    @Override
    public ApiMessage getAccountInfo(Dto dto) throws ApiException {
        //checkMerchantToken(dto);
        T_merchant_accountPO tMerchantAccountPO =daoMerchantAccount.getAccountMerchantId(dto.getString("merchantId"));
        if (SystemUtils.isEmpty(tMerchantAccountPO)){
            daoMerchantAccount.createAccount(dto.getString("merchantId"));
            tMerchantAccountPO =daoMerchantAccount.getAccountMerchantId(dto.getString("merchantId"));
        }
        return ApiMessageUtil.success(tMerchantAccountPO);
    }

    @Override
    @Transactional(propagation=Propagation.REQUIRED)
    public ApiMessage transferPointsToUser(Dto dto) throws ApiException {
        checkMerchantToken(dto);
        return apiCommonService.transferPointsToUser(dto);
    }

    @Override
    public ApiMessage merchantUserLogin(Dto dto) throws ApiException {
        checkMerchantToken(dto);
        T_userPO userPO=daoUser.selectByPhoneNum(dto.getString("phoneNum"));
        if (SystemUtils.isEmpty(userPO)){
            daoUser.createPhoneUser(dto);
            userPO=daoUser.selectByPhoneNum(dto.getString("phoneNum"));
        }
        T_accountPO accountPO =daoAccount.selectByUserId(userPO.getId());
        if (SystemUtils.isEmpty(accountPO)){
            daoAccount.createAccount(userPO);
            accountPO =daoAccount.selectByUserId(userPO.getId());
        }
        if ("0".equals(userPO.getIs_valid())) {
            log.error("用户已被停用，请联系客服");
            throw new ApiException(ReqEnums.REQ_USER_IS_NOT_VALID);
        }
        // 记录登录日志
        userPO.setIp(dto.getString("ip"));
        userPO.setDevice_num(dto.getString("deviceNum"));
        userPO.setModify_time(new Date());
        userPO.setLast_login_time(new Date());
        daoUser.updateByPrimaryKey(userPO);
        // 获取token值
        String token = ApiUtils.getTokenByUserPO(userPO);
        Dto outDto = Dtos.newDto();
        outDto.put("token", token);
        outDto.put("baseUrl",propertiesLoader.getProperty("merchant_lottery_index_url"));
        return ApiMessageUtil.success(outDto);
    }
}
